<?php

declare(strict_types=1);

namespace app\shop\controller\admin;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\library\Tree;
use app\shop\model\Category as CategoryModel;

/**
 * 商品分类
 */
class Category extends Backend
{
    
    public function initialize()
    {
        $this->model = new CategoryModel;
    }


    /**
     * 自定义商品分类列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $categories = $this->model->sheepFilter()->where('parent_id', 0)->order('weigh', 'desc')->order('id', 'desc')->select();

        return success('获取成功', $categories);
    }




    /**
     * 添加商品分类
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only([
            'name', 'style', 'description', 'weigh'
        ]);
        $this->svalidate($params, ".add");
        $categories = $this->request->param('categories', []);

        Db::transaction(function () use ($params, $categories) {
            $this->model->save($params);

            //递归处理分类数据
            $this->createOrEditCategory($categories, $this->model->id);
        });
        return success('保存成功');
    }


    /**
     * 自定义商品分类详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $category = $this->model->where('parent_id', 0)->findOrFail($id);

        $categories = $this->model->with('children.children')->where('parent_id', $category->id)->order('weigh', 'desc')->order('id', 'desc')->select();

        return success('获取成功', ['category' => $category, 'categories' => $categories]);
    }



    /**
     * 修改自定义商品分类
     *
     * @return \think\Response
     */
    public function edit($id)
    {
        $params = $this->request->only([
            'name', 'style', 'description', 'weigh'
        ]);
        $this->svalidate($params, ".edit");
        $categories = $this->request->param('categories', []);

        $category = $this->model->where('parent_id', 0)->findOrFail($id);

        Db::transaction(function () use ($category, $params, $categories) {
            $category->save($params);

            //递归处理分类数据
            $this->createOrEditCategory($categories, $category->id);
        });
        // 是供应链的时候
        if ($id == 1513) {
            // 同步萌宠霸王
            $cutepetDb             = Db::connect('mysql_cutepet');
            $parent_id = $cutepetDb->name('shop_category')->field('id, name, parent_id, status, weigh')->where('name', 'like', '%供应链商品%')->findOrEmpty();
            $mc_data = $cutepetDb->name('shop_category')->field('name, parent_id, image, description, status, weigh')->where('parent_id', '=', $parent_id['id'])->select()->toArray();

            $exist_data = Db::name('shop_category')->field('name,parent_id,image,description,status,weigh')->where('parent_id', $category->id)->select()->toArray();
            $categorys = $this->compareArraysByKey($mc_data, $exist_data, 'name');
            foreach ($categorys as $key => $value) {
                $value['parent_id'] = $parent_id['id'];
                unset($value['type_text'], $value['status_text']);
                $categorys[$key] = $value;
            }
            $cutepetGroupGoods     = $cutepetDb->name('shop_category')->insertAll($categorys);
            if (!$cutepetGroupGoods) {
                return error('同步萌宠霸王失败');
            }
        }
        return success('更新成功');
    }



    /**
     * 删除自定义商品分类
     *
     * @param string $id 要删除的商品分类列表
     * @return void
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->with('children')->whereIn('id', $id)->cursor() as $category) {
                if (!$category->children->isEmpty()) {
                    throw new SheepException('请先删除子分类');
                }
                $category->delete();
            }
        });

        return success('删除成功');
    }


    /**
     * 获取所有分类，商品选择
     *
     * @return \think\Response
     */
    public function select()
    {
        $categories = (new Tree(function () {
            // 组装搜索条件，排序等
            return $this->model->field("id, name, parent_id, status, weigh")->normal()
                    ->order('weigh', 'desc')->order('id', 'asc');
        }))->getTree(0);

        return success('获取成功', $categories);
    }


    /**
     * 商品列表左边分类
     *
     * @return void
     */
    public function goodsSelect()
    {
        $categories = $this->model->with(['children'])
        ->where('parent_id', 0)->order('weigh', 'desc')->order('id', 'desc')->select();

        return success('获取成功', $categories);
    }


    private function createOrEditCategory($categories, $parent_id)
    {
        foreach ($categories as $key => $data) {
            $data['parent_id'] = $parent_id;

            if (isset($data['id']) && $data['id']) {
                $category = $this->model->findOrFail($data['id']);

                if(isset($data['deleted']) && $data['deleted'] == 1) {
                    $category->delete();
                }else {
                    $category->name = $data['name'];
                    $category->parent_id = $data['parent_id'];
                    $category->image = $data['image'];
                    $category->description = $data['description'] ?? null;
                    $category->status = $data['status'];
                    $category->weigh = $data['weigh'];
                    $category->save();
                }
            } else {
                if (!isset($data['deleted']) || !$data['deleted']) {
                    $category = new CategoryModel;
                    $category->name = $data['name'];
                    $category->parent_id = $data['parent_id'];
                    $category->image = $data['image'];
                    $category->description = $data['description'] ?? null;
                    $category->status = $data['status'];
                    $category->weigh = $data['weigh'];
                    $category->save();
                    $data['id'] = $category->id;
                }
            }

            if (isset($data['children']) && !empty($data['children']) && isset($data['id'])) {
                $this->createOrEditCategory($data['children'], $data['id']);
            }
        }
    }

    function compareArraysByKey($array1, $array2, $key) {
        // 提取 array1 中指定键的值
        $keysInArray1 = array_column($array1, $key);

        // 过滤 array2，返回 array2 中指定键的值不在 array1 中的元素
        $result = array_filter($array2, function ($item) use ($keysInArray1, $key) {
            return !in_array($item[$key], $keysInArray1);
        });

        return $result;
    }
}
